import { FC, useEffect, useState } from "react";

import Loading from "../../../componets/loading";

import { Skeleton } from "antd-mobile";

import "../styled.scss";

interface Props {}
const Index: FC<Props> = () => {
  // 电影方法
  const [finished, setFinished] = useState(false);
  const [num, setNum] = useState(10);
  const getFilmHtml = () => {
    const temp = [];

    for (let i = 1; i <= num; i++) {
      //   temp.push(i);
      //   temp.push(<h1>{i}</h1>);  // [<h1>11</h1>, <h1>22</h1>]
      temp.push(
        <div className="film" key={i}>
          <div className="poster">
            <img
              src="https://static.maizuo.com/pc/v5/usr/movie/5eaa8e2163dc94074d800528df2e4ba5.jpg"
              alt=""
            />
          </div>
          <div className="info">
            <div className="title">
              复合吧！前任<span>2D</span>
            </div>
            <div className="comment">
              观众评分<span>7</span>
            </div>
            <div className="author">主演：陶亮 张一鸣 于文文</div>
            <div className="time">中国大陆 | 93分钟</div>
            <div className="address">南京市雨花台</div>
          </div>
          <div className="buy">购买</div>
        </div>
      );
    }

    return temp;
  };

  // 上拉
  useEffect(() => {
    // 获取网页
    const docEl = document.documentElement;
    // 监控网页滚动
    document.addEventListener("scroll", () => {
      if (finished) return;
      // - 2.1 获取滚动的高度
      const scrollTop = Math.ceil(docEl.scrollTop);
      // - 2.2 获取可见视口的高度
      const clientHeight = docEl.clientHeight;
      // - 2.3 获取内容总高度
      const totalHeight = docEl.scrollHeight;
      // - 2.4 判断 1+2>=3 则到底啦
      if (scrollTop + clientHeight >= totalHeight) {
        console.log("接口请求中..");
        setTimeout(() => {
          console.log("请求完毕 over");
          setNum(num + 10);

          // 每次拿到数据后判断是否到底啦
          if (num >= 50) {
            setFinished(true);
          }
        }, 2000);
      }
    });
  }, [num, finished]);

  // 骨架片
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    // 模拟接口请求
    setTimeout(() => {
      // 异步请求拿到电影数据后关闭loading
      setLoading(false);
    }, 4000);
  }, []);

  // 渲染
  return (
    <div className="films" style={{ marginTop: "-45px" }}>
      {loading ? (
        <>
          <Skeleton.Title animated />
          <Skeleton.Paragraph lineCount={5} animated />
          <Skeleton.Paragraph lineCount={5} animated />
        </>
      ) : (
        getFilmHtml()
      )}

      {finished ? (
        <h1 style={{ color: "#ccc", textAlign: "center" }}>到底啦~~</h1>
      ) : (
        <Loading />
      )}
    </div>
  );
};

export default Index;
